const express = require('express');
const net = require('net');
const path = require('path');
const bodyParser = require('body-parser');

const app = express();
const tcpClients = new Set();

// Express设置
app.use(express.static('public'));
app.use(bodyParser.json());

let shipData = []; // 存储船舶数据

// 数据格式化常量
const START_CHAR = String.fromCharCode(0x01);
const END_CHAR = String.fromCharCode(0x03);
const TARGET_SPLITER = String.fromCharCode(0x14);
const DATA_SPLITER = String.fromCharCode(0x10);

// 格式化单个船舶数据
function formatShipData(ship) {
    const values = [
        'aisship',
        ship.targetId,
        ship.name,
        ship.mmsi,
        ship.state,
        ship.rotation,
        ship.imo,
        ship.call,
        ship.speed,
        ship.center_lat,
        ship.center_lon,
        ship.course_ship,
        ship.course_land,
        ship.length,
        ship.width,
        ship.shiptype,
        ship.ETA,
        ship.draft,
        ship.aistype,
        ship.dest,
        ship.icontype,
        ship.settype,
        ship.unixtime,
        ship.anchor_lat,
        ship.anchor_lon,
        ship.anchor_unixtime,
        ship.radar_id,
        ship.radar_speed,
        ship.radar_course
    ];
    
    // 确保所有值都转换为字符串
    return values.map(v => v === undefined ? '' : String(v)).join(DATA_SPLITER);
}

// 格式化完整数据包
function formatCompleteData(ships) {
    if (!Array.isArray(ships) || ships.length === 0) {
        return START_CHAR + TARGET_SPLITER + END_CHAR;
    }
    const formattedShips = ships.map(formatShipData);
    return START_CHAR + TARGET_SPLITER + formattedShips.join(TARGET_SPLITER) + TARGET_SPLITER + END_CHAR;
}

// HTTP服务器
app.post('/send-message', (req, res) => {
    const message = req.body.message;
    // 向所有TCP客户端发送消息
    tcpClients.forEach(client => {
        client.write(message);
    });
    res.json({ success: true });
});

// 修改HTTP端点
app.post('/update-ships', (req, res) => {
    if (Array.isArray(req.body.ships)) {
        shipData = req.body.ships;
    }
    res.json({ success: true });
});

// 定时发送数据给所有TCP客户端
setInterval(() => {
    if (shipData.length > 0 && tcpClients.size > 0) {
        const formattedData = formatCompleteData(shipData);
        
        // 直接发送字符串数据，不进行JSON转换
        tcpClients.forEach(client => {
            try {
                client.write(formattedData, 'utf8');
            } catch (err) {
                console.error('Error sending data to client:', err);
                tcpClients.delete(client);
            }
        });
    }
}, 1000);

// TCP服务器
const tcpServer = net.createServer((socket) => {
    console.log('Client connected');
    tcpClients.add(socket);

    socket.on('end', () => {
        console.log('Client disconnected');
        tcpClients.delete(socket);
    });

    socket.on('error', (err) => {
        console.log('Socket error:', err);
        tcpClients.delete(socket);
    });
});

// 启动服务器
const HTTP_PORT = 3000;
const TCP_PORT = 3001;

app.listen(HTTP_PORT, () => {
    console.log(`HTTP Server running on port ${HTTP_PORT}`);
});

tcpServer.listen(TCP_PORT, () => {
    console.log(`TCP Server running on port ${TCP_PORT}`);
});
